import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

// Java 定制化通信例子
// 使用 Condition 
public class customerCommunication {
    public static void main(String[] args) {
        testPrint();
    }
    public static void testPrint(){
        shareResource sR = new shareResource();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    sR.printA(i);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"TA").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    sR.printB(i);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"TB").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    sR.printC(i);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"TC").start();
    }
}
// 资源类
class shareResource{
    // 标志位
    private int flag = 1;
    // 1 A 2 B 3 C
    private final ReentrantLock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    // loop 参数第 loop 轮
    public void printA(int loop) throws InterruptedException{
        lock.lock();
        try{
            while(flag != 1){
                c1.await();
            }
            System.out.println(Thread.currentThread().getName()+" print A "+" :轮数: "+loop);
            flag = 2;
            c2.signal();
        }
        finally{
            lock.unlock();
        }
    }

    public void printB(int loop) throws InterruptedException{
        lock.lock();
        try{
            while(flag != 2){
                c2.await();
            }
            System.out.println(Thread.currentThread().getName()+" print B "+" :轮数: "+loop);
            flag = 3;
            c3.signal();
        }
        finally{
            lock.unlock();
        }
    }

    public void printC(int loop) throws InterruptedException{
        lock.lock();
        try{
            while(flag != 3){
                c3.await();
            }
            System.out.println(Thread.currentThread().getName()+" print C "+" :轮数: "+loop);
            flag = 1;
            c1.signal();
        }
        finally{
            lock.unlock();
        }
    }
    
}
